#include "mainwindow.h"

#include <QApplication>

#include <QCoreApplication>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QFile>
#include <QDebug>

// 文件路径
const QString filePath = "data.xml";

// 1. 写入 XML 文件
void writeXmlFile() {
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly)) {
        qWarning() << "无法创建或打开文件: " << file.errorString();
        return;
    }

    QXmlStreamWriter writer(&file);
    writer.setAutoFormatting(true); // 自动格式化，使XML文件更易读

    writer.writeStartDocument(); // 写入XML文档头

    // 写入根元素 <books>
    writer.writeStartElement("books");

    // 写入第一个 <book> 元素
    writer.writeStartElement("book");
    writer.writeAttribute("id", "001");
    writer.writeTextElement("title", "Qt 编程实战");
    writer.writeTextElement("author", "张三");
    writer.writeTextElement("year", "2023");
    writer.writeEndElement(); // 结束 <book>

    // 写入第二个 <book> 元素
    writer.writeStartElement("book");
    writer.writeAttribute("id", "002");
    writer.writeTextElement("title", "C++ 高级编程");
    writer.writeTextElement("author", "李四");
    writer.writeTextElement("year", "2022");
    writer.writeEndElement(); // 结束 <book>

    writer.writeEndElement(); // 结束根元素 <books>
    writer.writeEndDocument(); // 结束XML文档

    qDebug() << "XML文件写入成功！";
    file.close();
}

// 2. 读取和解析 XML 文件
void readXmlFile() {
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qWarning() << "无法打开文件: " << file.errorString();
        return;
    }

    QXmlStreamReader reader(&file);

    qDebug() << "开始读取 XML 文件...";

    while (!reader.atEnd() && !reader.hasError()) {
        QXmlStreamReader::TokenType token = reader.readNext();

        if (token == QXmlStreamReader::StartDocument) {
            continue;
        }

        if (token == QXmlStreamReader::StartElement) {
            if (reader.name().toString() == "books") {
                qDebug() << "找到根元素: <books>";
            } else if (reader.name().toString() == "book") {
                QString id = reader.attributes().value("id").toString();
                qDebug() << "\n找到书籍，ID为: " << id;
            } else if (reader.name().toString() == "title") {
                QString title = reader.readElementText();
                qDebug() << "  标题: " << title;
            } else if (reader.name().toString() == "author") {
                QString author = reader.readElementText();
                qDebug() << "  作者: " << author;
            } else if (reader.name().toString() == "year") {
                QString year = reader.readElementText();
                qDebug() << "  年份: " << year;
            }
        }
    }

    if (reader.hasError()) {
        qWarning() << "XML解析出错: " << reader.errorString();
    }

    qDebug() << "\nXML文件读取完成。";
    file.close();
}

// 3. 修改 XML 文件中的元素 (修正版)
void modifyXmlFile() {
    QFile fileIn(filePath);
    if (!fileIn.open(QIODevice::ReadOnly)) {
        qWarning() << "无法打开文件进行修改: " << fileIn.errorString();
        return;
    }

    QByteArray xmlContent = fileIn.readAll();
    fileIn.close();

    QFile fileOut("temp.xml");
    if (!fileOut.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
        qWarning() << "无法创建临时文件: " << fileOut.errorString();
        return;
    }

    QXmlStreamReader reader(xmlContent);
    QXmlStreamWriter writer(&fileOut);
    writer.setAutoFormatting(true);

    while (!reader.atEnd() && !reader.hasError()) {
        QXmlStreamReader::TokenType token = reader.readNext();

        // 直接复制所有开始元素
        if (token == QXmlStreamReader::StartElement) {
            writer.writeStartElement(reader.name().toString());
            writer.writeAttributes(reader.attributes());

            // 判断是否是需要修改的 <book> 元素
            if (reader.name().toString() == "book" && reader.attributes().value("id").toString() == "001") {
                qDebug() << "正在修改 ID为001 的书籍标题...";

                // 遍历并复制 <book> 下的所有子元素
                while (reader.readNextStartElement()) {
                    if (reader.name().toString() == "title") {
                        // 遇到 <title>，写入新值
                        writer.writeTextElement("title", "Qt 6 高级编程与项目实战");
                        // 移动到旧的 <title> 结束标签
                        reader.readElementText();
                    } else {
                        // 其他子元素，直接复制
                        writer.writeTextElement(reader.name().toString(), reader.readElementText());
                    }
                }
                writer.writeEndElement(); // 结束 <book> 元素
            }
        }
        // 直接复制其他类型的节点
        else if (token == QXmlStreamReader::Characters && !reader.isWhitespace()) {
            writer.writeCharacters(reader.text().toString());
        } else if (token == QXmlStreamReader::EndElement) {
            writer.writeEndElement();
        }
    }

    fileOut.close();
    if (fileIn.remove()) {
        if (QFile::rename("temp.xml", filePath)) {
            qDebug() << "文件修改成功！";
        } else {
            qWarning() << "无法重命名文件!";
        }
    } else {
        qWarning() << "无法删除旧文件!";
    }
}

int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    // 演示流程
    writeXmlFile();
    qDebug() << "---------------------------";
    readXmlFile();
    qDebug() << "---------------------------";
    modifyXmlFile();
    qDebug() << "---------------------------";
    readXmlFile(); // 再次读取以验证修改

    return a.exec();
}
